import React, { useEffect, useState } from 'react';
import { Form, Button, Typography, Flex, message, Col } from 'antd';
import { useTranslation } from 'react-i18next';
import RequestUploadItem from '../../Components/RequestUploadItem';
import RequestFormProjectTpl from '../../Components/RequestFormProjectTpl';
import RequestFormProductTpl from '../../Components/RequestFormProductTpl';
import { useLocation, useNavigate } from 'react-router-dom';
import { apiSysTemplateInitiate } from '../../../services/common';
import { apiSynTouchRequestAdd, apiSynTouchRequestView, apiSynTouchRequestEdit } from '../../../services/synTouch/request';
import { ACCEPT_TYPE, REQUEST_PAGE, APPROVAL_STATUS, RES_MODE } from '../../../utils/constant';
import { getUserName, resquestDetialAttachmentListFormat, getPageOperationPermission, hasCampAdminRole, hasBuRole, getPagePermissionByUrl, formatRequestItemData } from '../../../utils/commonUtil';
import _ from 'lodash';
import RequestApprovalBtn from '../../Components/RequestApprovalBtn';
import { PAGE_PERMISSION_CHECK } from '../../../utils/pagePermission';

const { Title } = Typography;
const SynTouchRequestDetails = () => {
  const { APPROVED, REJECTED, PENDING, DRAFT } = APPROVAL_STATUS;
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const location = useLocation();
  const [hasAddAndDelete, setHasAddAndDelete] = useState(false);
  const [hasImportTestData, setHasImportTestData] = useState(false);

  if (!location?.state) {
    navigate('/synTouch/list');
  };
  const queryParams = location?.state || {};
  const { tplId, tBu, synTouchProjectId, editMode, approveRequestSituationId, tMd, tTm } = queryParams;
  const [initialValues, setInitialValues] = useState();


  // mock permission
  const isCampAdmin = true;
  const isBuPRPD = false;
  const isBuAdmin = false;
  const isBuTester = false;

  const apiSynTouchRequestSaveAsync = async (type) => {
    const formData = form?.getFieldsValue();
    const prjData = {
      product: formData?.product,
      project: formData?.project,
      userId: getUserName(),
      operationType: type,
    };
    const data = editMode === RES_MODE.NEW ? await apiSynTouchRequestAdd(prjData) : await apiSynTouchRequestEdit(prjData);
    // console.log(data);
    if (data?.data?.code === 200) {
      message.success(t('common.saveSuccess'));
      navigate('/synTouch/list')
    }
  };
  const saveClickHandle = (type) => {
    // console.log(form.getFieldsValue());
    form.validateFields().then(() => {
      apiSynTouchRequestSaveAsync(type);
    }, () => {
      return false;
    });
  };
  // xml附件部分
  const productExtraContentrRender = (index) => {
    const listNames = 'product';
    const fileList = resquestDetialAttachmentListFormat(initialValues?.[listNames]?.[index]?.attachmentUrl?.fieldValue);
    return (
      <Col span={24}>
        <Form.Item
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          name={[index, 'attachmentUrl']}
          label=''>
          <RequestUploadItem
            btnText={t('synTouch.uploadXml')}
            acceptType={ACCEPT_TYPE.XML}
            disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW}
            uploadUpdateFn={({ fileList, deleteFileList }) => {
              const productData = form?.getFieldsValue()?.[listNames];
              const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
              productData[index] = {
                ...productItemData,
                attachmentUrl: {
                  fieldName: 'attachmentUrl',
                  fieldValue: fileList,
                  fieldDeleteValue: deleteFileList,
                }
              };
              form.setFieldsValue({
                [listNames]: productItemData,
              });
              // form.validateFields([listNames]);
            }}
            fileListData={fileList}
          />
        </Form.Item>
      </Col>
    )
  };

  // 操作鉴权
  const operateAuthentication = () => {
    // 新增和删除权限
    const permissionList = getPagePermissionByUrl(PAGE_PERMISSION_CHECK, '/synTouch/list');
    const addAndDeletePermission = getPageOperationPermission(permissionList, 'addAndDelete');
    const hasAddAndDelete = hasCampAdminRole(addAndDeletePermission) || hasBuRole(addAndDeletePermission);
    setHasAddAndDelete(hasAddAndDelete);

    // 编辑权限
    const importTestDataPermission = getPageOperationPermission(permissionList, 'importTestData');
    const hasImportTestData = hasCampAdminRole(importTestDataPermission) || hasBuRole(importTestDataPermission);
    setHasImportTestData(hasImportTestData);
  };

  useEffect(() => {

    operateAuthentication();
    // 获取模板数据
    let initData = {};
    if (tplId && editMode === RES_MODE.NEW) {
      apiSysTemplateInitiate({ templateName: tTm, buType: tBu, moduleName: tMd }).then((res) => {
        if (res?.data?.code === 200) {
          initData = {
            project: res?.data?.data?.Project,
            product: [
              {
                ...res?.data?.data?.Product
              }
            ]
          };
          setInitialValues(initData);
        }
      })
    } else if (synTouchProjectId && (editMode === RES_MODE.APPROVAL || editMode === RES_MODE.VIEW || editMode === RES_MODE.EDIT || editMode === RES_MODE.TESTEREDIT)) {
      apiSynTouchRequestView({
        synTouchProjectId: synTouchProjectId,
        userId: getUserName(),
      }).then((res) => {
        if (res?.data?.code === 200) {
          const newProject = formatRequestItemData(res?.data?.data?.item?.project);
          const newProduct = res?.data?.data?.item?.product?.map((prdItem) => {
            return formatRequestItemData(prdItem)
          });
          initData = {
            project: newProject,
            product: newProduct,
          };
          setInitialValues(initData);
        }
      })
    };
  }, []);

  return (
    <>
      {
        initialValues &&
        <>
          <div className='page-title-wrap'>
            <Flex align='center' justify='space-between'>
              <Title className='fontStyleH2' level={2} >{editMode === RES_MODE.NEW ? t(`common.newRequest`) : t(`common.requestDetail`)}</Title>
              <div>
                <RequestApprovalBtn
                  approveRequestSituationId={approveRequestSituationId}
                  form={form}
                  moduleConfig={REQUEST_PAGE['SynTouch']}
                  initialValues={initialValues}
                  editMode={editMode}
                />
                {
                  (
                    //可填写测试数据 save
                    (hasImportTestData && initialValues?.project?.requestStatus?.fieldValue === APPROVED) ||
                    //可重新编辑 save
                    (hasAddAndDelete && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || initialValues?.project?.requestStatus?.fieldValue === APPROVED || editMode === RES_MODE.NEW))
                  ) && editMode !== RES_MODE.VIEW &&
                  <Button onClick={() => { saveClickHandle('save') }} style={{ marginRight: '10px' }}>{t('common.save')}</Button>
                }
                {

                  //可重新编辑 submit
                  hasAddAndDelete && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || editMode === RES_MODE.NEW) && editMode !== RES_MODE.VIEW &&
                  <Button type='primary' onClick={() => { saveClickHandle('submit') }}>{t('common.submit')}</Button>
                }
              </div>
            </Flex>
          </div>
          <div className='page-content-wrap'>
            <Form form={form}
              initialValues={initialValues}
              disabled={editMode === RES_MODE.VIEW || editMode === RES_MODE.TESTEREDIT || editMode === RES_MODE.APPROVAL}
            >
              {/* Project */}
              <RequestFormProjectTpl
                uploadParams={{ type: 'synTouch', name: 'project' }}
                tplData={queryParams}
                listNames='project'
                form={form}
                initialValues={initialValues}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['SynTouch']}
              />
              {/* Product */}
              <RequestFormProductTpl
                uploadParams={{ type: 'synTouch', name: 'product' }}
                listNames='product'
                form={form}
                initialValues={initialValues}
                productExtraContentrRender={productExtraContentrRender}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['SynTouch']}
              />
            </Form>
          </div>
        </>
      }
    </>
  )
};

export default SynTouchRequestDetails;
